﻿using MyWebApp.Common.Entity;
using MyWebApp.Common.Exceptions;
using MyWebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace MyWebApp.Common
{
    public class AuthUtil
    {
        /// <summary>
        /// 检查是否登录
        /// </summary>
        /// <param name="Context"></param>
        /// <returns></returns>
        public static bool CheckLogin(HttpContextBase Context)
        {
            if (Context.Session[Constant.CurrentUser] == null)
            {
                //检查cookie
                var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null && (cookie.Expires == DateTime.MinValue || cookie.Expires > DateTime.Now))
                {
                    var ticket = FormsAuthentication.Decrypt(cookie.Value);
                    if (ticket != null && ticket.Expired == false)
                    {
                        //更新session
                        return doReLogin(ticket.UserData);
                    }
                }
            }
            else
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 用户重登陆
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static bool doReLogin(string userid)
        {
            if (!string.IsNullOrEmpty(userid))
            {
                var user = new LoginUserModel
                {
                    UserId = "admin",
                    UserName = "管理员",
                    UserDept = "研发",
                    UserImg = "a.png",
                    RememberMe = true,
                    Password = "",
                    Remarks = "没得说的",
                    Roles = new List<string>()
                };
                user.Roles.Add("管理员");
                user.Roles.Add("测试");
                user.Roles.Add("开发");
                HttpContext.Current.Session[Constant.CurrentUser] = user;
                return true;
            }
            return false;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool doLogin(string userid, string pwd, bool rememberMe = false)
        {
            if (!string.IsNullOrEmpty(userid) && userid == "admin" && pwd == "1")
            {
                //登录成功
                var user = new LoginUserModel
                {
                    UserId = "admin",
                    UserName = "管理员",
                    UserDept = "研发",
                    UserImg = "a.png",
                    RememberMe = rememberMe,
                    Password = "",
                    Remarks = "没得说的",
                    Roles = new List<string>()
                };
                user.Roles.Add("管理员");
                user.Roles.Add("测试");
                user.Roles.Add("开发");
                HttpContext.Current.Session[Constant.CurrentUser] = user;

                if (rememberMe)
                {
                    //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user.UserId, true, 30);

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                    (1,
                        user.UserId,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(60),
                        true,
                        user.UserId   //用户数据 可用于鉴权
                    );
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.Expires = DateTime.Now.AddDays(1);
                    cookie.HttpOnly = true;
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        /// <returns></returns>
        public static LoginUserModel GetCurrentUser()
        {
            return HttpContext.Current.Session[Constant.CurrentUser] as LoginUserModel;
        }

        public static string GetCurrentUserID()
        {
            var u = GetCurrentUser();
            if (u != null)
            {
                return u.UserId;
            }
            return string.Empty;
        }

        public static bool CheckUserRight(HttpContextBase Context)
        {
            string url = Context.Request.Path;
            if (GetCurrentUser() == null)
            {
                throw new SessionTimeoutException();
            }
            var roles = GetCurrentUser().Roles;

            //临时
            //todo  通过数据库检查 url 与roles 是否匹配
            if (roles.Contains("管理员") || roles.Contains("admin"))
            {
                return true;
            }
            return false;
        }
    }
}